/*
 * @Descripttion: 
 * @Author: junhuafly
 * @Date: 2020-02-28 14:27:03
 * @LastEditors: junhuafly
 * @Email: junhuafly@163.com
 * @LastEditTime: 2020-04-20 12:00:01
 */
// pages/post/index.js
import {
  userAPI
} from './../../api/user'

import {
  returnStatus,
  UploadFile
} from './../../utils/index'
import Notify from './../../@vant/weapp/dist/notify/notify';
import {
  noteAPI
} from '../../api/note';
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    active: '相册',
    showTags: false,
    showError: false,
    goods: [],
    fileList: [],
    customerTag: [],
    form: {
      "noteContent": "",
      "noteStatus": 0,
      "noteType": 0,
      "products": [],
      "tags": [],
      "title": "",
      images:[]
    },
    nvabarData:{
      showCapsule:1
    }
  },

  // 选择标签
  onShowTags() {
    const _this = this
    wx.navigateTo({
      url: '/pages/post/tags/index',
      events: {
        getTags({
          data
        }) {
          data.map(item => {
            _this.data.form.tags.push(item.tagId)
          })
          _this.setData({
            customerTag: data
          })
        }
      },
      success: (result) => {
        const tags = this.data.customerTag.map(item => {
          return item.tagId + ''
        })
        result.eventChannel.emit('params', tags)
      },
      fail: () => {},
      complete: () => {}
    });
  },

  // 删除带货商品
  onRemoveGoods({
    target
  }) {
    const {
      index
    } = target.dataset
    this.data.goods.splice(index, 1)
    this.setData({
      goods: this.data.goods
    })

  },

  // 选择商品
  chooseGoods() {
    const _this = this
    wx.navigateTo({
      url: '/pages/post/shops/index',
      events: {
        goods(goods) {
          _this.setData({
            goods
          })
        }
      },
      success: (result) => {
        const values = this.data.goods.map(item => {
          return item.productId + ''
        })
        result.eventChannel.emit('params', values)
      },
      fail: () => {},
      complete: () => {}
    });
  },
  // 发布笔记
  async onPost({
    target: {
      dataset: {
        type
      }
    }
  }) {

    // 添加带货商品
    this.data.goods.map(item => {
      this.data.form.products.push(item.productId)
    })
    const fileRescore = this.data.fileList
    if (fileRescore.length > 5) {
      wx.showToast({
        title: '最多上传5张图片',
        icon: 'none',
        duration: 800,
      });
    }
    let files = []
    fileRescore.forEach(item => {
      !item.noteId&&files.push(item.url)
    })
    let images = []
    if(files.length){
      const _ = await UploadFile.upload(files, 'NOTE', (progress) => {})
      const len = this.data.form.images.length
      if (_ && _.length === files.length) {
        _.forEach((item, index) => {
          try {
            const res = JSON.parse(item)
            console.log(res)
            if (res.code === 200) {
              const sIndex = len+index
              images.push({
                "height": fileRescore[sIndex].sHeight,
                "noteImageUrl": res.data,
                "seq": sIndex+1,
                "ratio": parseFloat(fileRescore[sIndex].ratio),
                "width": fileRescore[sIndex].sWidth
              })
            }
          } catch (error) {
            wx.showToast({
              title: '解析上传返回结果出错',
              icon: 'none',
              duration: 800,
            });
          } finally {
            wx.hideToast();
          }
        })
      }
    }
    this.data.form.images=[...this.data.form.images,...images]
    this.verifyVal()
    wx.showLoading({
      title: '发布中...',
      mask: true,
    });
    this.data.form.noteStatus = type === 'draft' ? 2 : 0
    const publishRes = await noteAPI.handleNote({
      method: 'post',
      ...this.data.form
    })
    const noteId = await returnStatus(publishRes)
    // 发布成功跳转到首页
    if (noteId) {
      wx.hideLoading();
      app.data.globalParams = noteId
      wx.showToast({
        title: publishRes.message,
        icon: 'success',
        duration: 800,
        success: (result) => {
          wx.switchTab({
            url: `/pages/note/index`,
          });
        },
      });
    }

    return
  },
  verifyVal() {
    const obj = {
      title: '标题',
      noteContent: '笔记内容',
      images: '图片'
    }
    for (const key in obj) {
      const temp = this.data.form[key]
      if (!temp || !temp.length) {
        Notify({
          type: 'danger',
          message: `“ ${obj[key]} ”不能为空~`,
          duration: 800
        });
        return
      }
    }
    return
  },
  // 删除图片
  onDelImage({
    detail
  }) {
    const {
      index
    } = detail
    const fileList = this.data.fileList
    fileList.splice(index, 1)
    this.setData({
      fileList,
      showError: fileList.length > 5
    })
  },
  // 获取图片
  async handleImage({
    detail
  }) {
    const {
      file
    } = detail
    const _this = this
    if (this.data.fileList.length + file.length > 5) {
      this.setData({
        showError: true
      })
    }
    wx.navigateTo({
      url: '/pages/cropper/index',
      events: {
        async cropperSuccess({
          data
        }) {
          for (const key in data) {
            const {
              path: url,
              sWidth,
              sHeight,
              ratio
            } = data[key]
            _this.data.fileList.push({
              url,
              sWidth,
              sHeight,
              ratio
            })
          }
          console.log(_this.data.fileList)
          _this.setData({
            fileList: _this.data.fileList
          })
        }
      },
      success(res) {
        res.eventChannel.emit('propsObj', {
          data: {
            minBoxWidthRatio: 0.8,
            aspectRatio: '0.95',
            aspectRatios: _this.data.form.images.length?_this.data.form.images[0].ratio:['0.95', '0.77'],
            backUrl: '/pages/post/index',
            images: file
          }
        })
      }
    })
  },

  //获取文本信息
  onChange({
    detail,
    target: {
      dataset: {
        type
      }
    }
  }) {
    const key = `form.${type}`
    this.setData({
      [key]: detail
    })
  },

  onCancel() {
    this.setData({
      showTags: false
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 从草稿中 
    var appInst =  getApp();
    appInst.setTitle('发布笔记')
    
    const event = this.getOpenerEventChannel()
    event.on('params',({noteId})=>{
      noteAPI.queryNoteDetailInit({noteId}).then(async res=>{
        const {images:i,details:d} = await returnStatus(res)
        this.setData({
          'form.noteContent':d.noteContent,
          'form.title':d.title,
          'form.images':i,
          'form.noteId':d.noteId
        })
        let fileList = []
        i.forEach(item=>{
          item.url = item.noteImageUrl
          fileList.push(item)
        })
        this.setData({
          fileList
        })
      })
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },



  // 下面测试拖拽

  change(e) {
    console.log("change", e.detail.listData)
  },
  sizeChange(e) {
    wx.pageScrollTo({
      scrollTop: 0
    })
    this.setData({
      size: e.detail.value
    });
    this.drag.init();
  },
  itemClick(e) {
    console.log(e);
  },
  toggleFixed(e) {
    let key = e.currentTarget.dataset.key;

    let {
      listData
    } = this.data;

    listData[key].fixed = !listData[key].fixed

    this.setData({
      listData: listData
    });

    this.drag.init();
  },
})